package com.blockmeta.bbs.immodule.corebean.Impl;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.net.callback.FileUploadCallBack;
import com.blockmeta.bbs.baselibrary.utils.ImageTools;
import com.blockmeta.bbs.immodule.corebean.IFileHttpService;
import com.blockmeta.bbs.businesslibrary.util.Update2QiniuCloud;
import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.compress.CompressImage;
import org.devio.takephoto.compress.CompressImageImpl;
import org.devio.takephoto.model.LubanOptions;
import org.devio.takephoto.model.TImage;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

public class FileHttpService implements IFileHttpService {


    private Context mContext;
    //记录文件上传下载进度
    private HashMap<String, Integer> fileDownLoadUploadProgress;

    public FileHttpService(Context context) {
        mContext = context;
        this.fileDownLoadUploadProgress = new HashMap<>();
    }

    @Override
    public int getFileProgress(String url) {
        Integer progress = fileDownLoadUploadProgress.get(url);
        if (progress == null) {
            return 0;
        }
        return progress;
    }


    @Override
    public void uploadImImage(final Context mContext, final String url, final IMFileUploadCallBack callBack) {
            //获取文件名称
            final String fileName = url.substring(url.lastIndexOf(File.separator) + 1);

            //使用takephoto中的luban压缩图片到应用cache目录，单张
            LubanOptions lubanOptions = new LubanOptions.Builder().setMaxHeight(1500).setMaxWidth(1500).setMaxSize(1000000).create();
            CompressConfig compressConfig = CompressConfig.ofLuban(lubanOptions);
            ArrayList<TImage> tImages = new ArrayList<>();
            tImages.add(TImage.of(url, TImage.FromType.OTHER));
            CompressImageImpl.of(mContext, compressConfig, tImages, new CompressImage.CompressListener() {
                @Override
                public void onCompressSuccess(ArrayList<TImage> images) {

                    try {
                        String compressPath = images.get(0).getCompressPath();
                        final int[] fileSize = ImageTools.getFileSize(compressPath);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("w", fileSize[0] + "");
                        jsonObject.put("h", fileSize[1] + "");

                        final String fileParam = jsonObject.toString();
                        //上传完成需要删除压缩后的图片，现在发现takephone有自带压缩功能，不过先用自己写的
                        final String needDeleteFileUrl = compressPath;
                        Update2QiniuCloud.postFileToNet(mContext, "", needDeleteFileUrl, new FileUploadCallBack() {
                            @Override
                            public void fail(String msg) {
                                if (callBack != null) {
                                    callBack.fail(msg);
                                }
                            }

                            @Override
                            public void progress(int progress) {
                                fileDownLoadUploadProgress.put(needDeleteFileUrl, progress);
                                if (callBack != null) {
                                    callBack.progress(progress);
                                }
                            }

                            @Override
                            public void success(String s) {
                                fileDownLoadUploadProgress.put(needDeleteFileUrl, 100);
                                //删除发送的压缩后保存的图片
                                try {
                                    LogUtils.d("author delete img" + needDeleteFileUrl);
                                    //使用鲁班压缩的会有鲁班前缀，有些地址是为压缩之前的图片
                                    if(needDeleteFileUrl.contains("Luban_")){
                                        File file = new File(needDeleteFileUrl);
                                        boolean result = file.delete();
                                    }
                                } catch (Exception e) {
                                    Log.d("author", "im send image then delete error" + e.getMessage());
                                }
                                if (callBack != null) {
                                    callBack.success(s, fileName, fileParam);
                                }
                            }
                        });


                    } catch (Exception e) {
                        LogUtils.d("uploadimage error " + e.getMessage());
                    }

                }

                @Override
                public void onCompressFailed(ArrayList<TImage> images, String msg) {

                }
            }).compress();

//            final File uploadFile = ImageTools.compressFile(url, dir.getAbsolutePath() + File.separator + jobId, 40, 0, 0, Bitmap.CompressFormat.JPEG);
            //获取压缩后的图片的大小

        }


        @Override
        public void downLoadFile ( final String filePath, final String fileName,
        final IMFileDownLoadCallBack imFileDownLoadCallBack){
            String externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            final String downLoadFileName = externalStoragePublicDirectory + File.separator + fileName;
            Log.d("downloadfile1", downLoadFileName);

            byte status = FileDownloader.getImpl().getStatus(filePath, downLoadFileName);
            Log.d("downloadfile2", downLoadFileName);
            FileDownloader.getImpl().create(filePath)
                    .setAutoRetryTimes(1)
                    .setPath(downLoadFileName)
                    .setListener(new FileDownloadListener() {

                        @Override
                        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        }

                        @Override
                        protected void started(BaseDownloadTask task) {
                        }

                        @Override
                        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        }

                        @Override
                        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                            int progress = soFarBytes * 100 / totalBytes;
                            fileDownLoadUploadProgress.put(filePath, progress);
                            imFileDownLoadCallBack.progress(progress);
                        }

                        @Override
                        protected void blockComplete(BaseDownloadTask task) {
                        }

                        @Override
                        protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                        }

                        @Override
                        protected void completed(BaseDownloadTask task) {
                            fileDownLoadUploadProgress.put(filePath, 100);
                            imFileDownLoadCallBack.success(filePath, downLoadFileName);
                        }

                        @Override
                        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        }

                        @Override
                        protected void error(BaseDownloadTask task, Throwable e) {
                        }

                        @Override
                        protected void warn(BaseDownloadTask task) {
                        }
                    }).start();
        }


        @Override
        public void uploadFile (Context mContext,final String url,
        final IMFileUploadCallBack callBack){
            //获取源文件名称
            final String fileName = url.substring(url.lastIndexOf(File.separator) + 1);
            //获取文件基本信息，如大小
            final JSONObject jsonObject = new JSONObject();

            File file = new File(url);
            if (file.exists() && file.isFile()) {
                try {
                    long fileSize = file.length();
                    if (fileSize > 200 * 1024 * 1024) {
                        return;
                    }
                    jsonObject.put("size", fileSize);
                } catch (JSONException e) {
                    e.printStackTrace();
                    return;
                }
            }


            Update2QiniuCloud.postFileToNet(mContext, "", url, new FileUploadCallBack() {
                @Override
                public void fail(String msg) {
                    callBack.fail(msg);
                }

                @Override
                public void progress(int progress) {
                    LogUtils.d("author" + "uploadFile progress" + progress);
                    fileDownLoadUploadProgress.put(url, progress);
                    callBack.progress(progress);

                }

                @Override
                public void success(String s) {
                    fileDownLoadUploadProgress.put(url, 100);
                    //删除发送的压缩后保存的图片
                    callBack.success(s, fileName, jsonObject.toString());
                }
            });

        }


    }
